<template>
  <div class="timesheet-container">
    <!-- 日历和表格区域 -->

    <div class="content-area">
      <!-- 左侧日历  @click="getformDatalist(currentDateqw)"-->
      <div class="calendar-section">
        <el-calendar
          v-model="currentDateqw"
          :first-day-of-week="1"
          @click="getlist(currentDateqw)"
        >
          <template #date-cell="{ data }">
            <p :class="getCellStyle(data.day)" style="line-height: 70px">
              {{ data.day.split("-").slice(2).join("-") }}
            </p>
          </template>
        </el-calendar>
      </div>

      <!-- 右侧工时表格 -->
      <div class="timesheet-section">
        <!-- loading组件 -->
        <div style="margin-bottom: 8px">
          <el-button type="primary" v-if="tijiaoflack" plain @click="tijiao"
            >提交审核</el-button
          >
        </div>
        <div>
          <el-table v-loading="loading" :data="formattedData" border style="width: 100%">
            <el-table-column
              label="姓名"
              prop="username"
              width="80"
              v-if="!loading"
            ></el-table-column>

            <el-table-column label="类型" width="60" v-if="!loading">
              <template #default="scope">
                <div>
                  {{ scope.row.full_work == "1" ? "全职" : "兼职" }}
                </div>
              </template>
            </el-table-column>

            <!-- 动态生成列 -->
            <el-table-column
              v-for="day in weekDays"
              :key="day"
              :label="day"
              v-if="!loading"
            >
              <template #default="scope">
                <!-- <el-tooltip content="详情" placement="right" offset="-8" effect="light"> -->
                <div
                  style="width: 100%; cursor: pointer; margin: 0 auto; padding: 0"
                  @click="handleClick(scope.row, day)"
                >
                  <div
                    v-if="getScheduleInfo(scope.row.scheduleMap, day)[1] == '无排班'"
                    :class="[
                      true && 'getScheduleInfostyle',
                      getScheduleInfo(scope.row.scheduleMap, day)[0] == '2' &&
                        'getScheduleInfostylecorlor',
                      getScheduleInfo(scope.row.scheduleMap, day)[0] == '1' &&
                        'paixiucoler',
                    ]"
                  >
                    {{ getScheduleInfo(scope.row.scheduleMap, day)[1] }}
                  </div>

                  <el-popover v-else placement="top" trigger="hover">
                    <el-button
                      type="danger"
                      size="small"
                      :disabled="isDeleteschedule(scope.row.scheduleMap, day)"
                      @click="deleteschedule(scope.row.scheduleMap, day)"
                      plain
                      >删除当前排班 ？</el-button
                    >
                    <template #reference>
                      <div
                        :class="[
                          true && 'getScheduleInfostyle',
                          getScheduleInfo(scope.row.scheduleMap, day)[0] == '2' &&
                            'getScheduleInfostylecorlor',
                          getScheduleInfo(scope.row.scheduleMap, day)[0] == '1' &&
                            'paixiucoler',
                        ]"
                      >
                        {{ getScheduleInfo(scope.row.scheduleMap, day)[1] }}
                      </div>
                    </template>
                  </el-popover>
                </div>

                <!-- </el-tooltip> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 班次修改弹框 -->

    <el-drawer
      v-if="dialogVisible"
      v-model="dialogVisible"
      size="500"
      :with-header="false"
    >
      <el-scrollbar height="100%">
        <div style="font-size: 20px; margin-bottom: 15px; font-weight: 600">
          {{ `日期为 ${heardtital}` }}
        </div>
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="110px"
          style="width: 100%; overflow: hidden; padding-right: 18px"
          :disabled="zhoujinzhi"
        >
          <div
            v-if="showvaction"
            style="
              background-color: #ecf5ff;
              border-radius: 10px;
              overflow: hidden;
              padding-right: 6px;
            "
          >
            <div class="form-section">
              <div class="form-section"></div>
              <div
                class="section-title"
                style="
                  margin-bottom: 12px;
                  transform: translateX(6px);
                  font-weight: 600;
                  margin-top: 10px;
                  font-size: 15px;
                "
              >
                请勾选选项
              </div>

              <el-form-item label="假期明细">
                <el-button type="primary" @click="vacationlog(true)" plain
                  >查看</el-button
                >
              </el-form-item>

              <el-form-item label="假期余额">
                <span style="margin-right: 20px" v-for="item in vacationyve">{{
                  `${item.leaveName} '${item.quota_num}' 天`
                }}</span>
              </el-form-item>

              <el-form-item label="选项" prop="vacationtype">
                <span style="transform: translate(-140%, 40%)">休假</span>
                <el-radio-group size="small" v-model="formData.vacationtype">
                  <div style="width: 100%; border-bottom: 1px solid #0e151d">
                    <el-radio value="200">正常上班</el-radio>
                  </div>
                  <div style="width: 100px">
                    <el-radio v-for="item in vacationyve" :value="item.leave_code">{{
                      item.leaveName
                    }}</el-radio>
                  </div>
                </el-radio-group>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlecancel">取消</el-button>
          <el-button :disabled="zhoujinzhi" type="primary" plain @click="handleSubmit"
            >保存</el-button
          >
        </div>
      </template>
    </el-drawer>

    <el-dialog
      v-model="dialogTableVisible"
      title="请选择假期类型查看"
      :close-on-click-modal="false"
      width="380"
    >
      <el-radio-group v-model="getVacationloglist" style="width: 100%">
        <el-radio
          v-for="item in vacationyve"
          :value="item.leave_code"
          style="width: 40%; display: inline-block"
          >{{ item.leaveName }}</el-radio
        >
      </el-radio-group>

      <el-table :data="vacationlogdata" style="width: 100%" height="230">
        <el-table-column label="假期周期">
          <template #default="scope">
            <span>{{ deteqiege(scope.row.years) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="假期余额">
          <template #default="scope">
            <span>{{ scope.row.numbers }} 天</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, reactive, onBeforeMount, watch } from "vue";
import { ElTable, ElTableColumn, ElButton, ElMessage, FormInstance } from "element-plus";
import { updateVacationBalance } from "@/api/vacation";
import {
  getscheduleList,
  unbdatascheduleList,
  putscheduleList,
  deleteransfer,
  vacationpost,
  getschedulemonth,
  delschedule,
} from "@/api/schedulingManage";

import "element-plus/dist/index.css";
import { getVacationlog } from "@/api/vacation";

import { schedulingManageStore } from "@/stores/schedulingManage";
const schedulingManageStoreData = schedulingManageStore();
const scheduledata = schedulingManageStoreData.getshopData();

import { formatDateToYearAndMonthDay } from "@/utils/date";

import {
  schedulingManagetype,
  midwayBreaktype,
  vacationyvetype,
} from "@/types/schedulingManageTYpe";

// 弹框
const dialogVisible = ref(false);
// 加载值
const loading = ref(true);

// // 从服务器获取的签到记录
// // 提交为已经通过
// const checkInDates1 = ref([]);

// // 提交为待审核
// const checkInDates3 = ref([]);

// // 提交为拒绝
// const checkInDates4 = ref([]);
// // 已经提交人的id

const MonthFlags: {
  [x: string]: any;
} = ref({});

// const WeekFlags: {
//   [x: string]: any;
// } = ref({});

// 首次加载需要的日期
const currentDateqw = ref(new Date());

const tijiaoflack = ref(false);

// 日历显示绿色
const getCellStyle = (date: string) => {
  if (MonthFlags.value[date] == "1") {
    return "signed-in1";
  } else if (MonthFlags.value[date] == "3") {
    return "signed-in3";
  } else if (MonthFlags.value[date] == "4") {
    return "signed-in4";
  } else {
    return " ";
  }

  // if (checkInDates1.value.includes(date)) {
  //   return "signed-in1";
  // } else if (checkInDates3.value.includes(date)) {
  //   return "signed-in3";
  // } else if (checkInDates4.value.includes(date)) {
  //   return "signed-in4";
  // } else {
  //   return " ";
  // }
};

// 日历选中发给后台的时间
const selecttoday = ref(" ");

// 获取当天的时间
onBeforeMount(() => {
  const aa = new Date();
  selecttoday.value = formatDateToYearAndMonthDay(aa);
});

// 没有信息时展示用于动态创建列表
const weekDays = ref([
  "星期天",
  "星期一",
  "星期二",
  "星期三",
  "星期四",
  "星期五",
  "星期六",
]);

//查看假期日志
const dialogTableVisible = ref(false);
const getVacationloglist = ref("SHCODE");
const vacationuseridlog = ref("");
const vacationlogdata = ref();
const deteqiege = (val: {
  toString: () => {
    (): any;
    new (): any;
    length: number;
    slice: { (arg0: number, arg1: number): string; new (): any };
  };
}) => {
  let tate = "";
  let tates = "";
  let conute = "";
  if (val.toString().length == 4) {
    tate = val.toString().slice(0, 4);
    conute = `${tate}年`;
  } else {
    tate = val.toString().slice(0, 4);
    tates = val.toString().slice(4, val.toString().length);
    conute = `${tate}年${tates}月`;
  }
  return conute;
};

const transformvacationlog = (data: { quota_cycle: any; quota_num: any }[]) =>
  data.map(({ quota_cycle, quota_num }) => ({
    years: quota_cycle,
    numbers: quota_num,
  }));

//假期日志
const vacationlog = async (val?: boolean) => {
  const res = await getVacationlog({
    leave_code: getVacationloglist.value,
    userid: vacationuseridlog.value,
  });

  vacationlogdata.value = transformvacationlog(res.data) || [];

  if (val) {
    dialogTableVisible.value = true;
  }
};

watch(getVacationloglist, (newval, olldval) => {
  getVacationloglist.value = newval;
  vacationlog(true);
});

// 排班信息的获取
const getformDatalist = async (val?: any) => {
  try {
    if (val) {
      loading.value = true;
      const aa = new Date(currentDateqw.value);
      selecttoday.value = formatDateToYearAndMonthDay(aa);
    }

    const response = await getscheduleList({
      shop_id: scheduledata.selfid,
      day: selecttoday.value,
    });

    if (response.code == "200") {
      if (val) {
        ElMessage.success("查询成功");
      }

      if (response.data.length > 0 && !(typeof response.data == "string")) {
        response.data[0].scheduleList.forEach(
          (element: { flag: string; day: string; week: any }, key: any) => {
            const as = element.day.toString();
            const aa = as.split(" ");
            const bb = aa[0].split("-");

            weekDays.value[key] = `${element.week} ${bb[0]}-${bb[1]}-${bb[2]}`;
          }
        );
      }

      if (val) {
        loading.value = false;
      }
    } else {
      if (val) {
        loading.value = false;
        ElMessage.error("查询失败");
      }
    }

    rawData.value = response.data;
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};

// 点击发送请求获取本周数据
const getlist = (val?: any) => {
  loading.value = true;
  // checkInDates1.value = [];
  // checkInDates3.value = [];
  // checkInDates4.value = [];

  MonthFlags.value = {};
  // WeekFlags.value = {};

  if (val) {
    const newdate = new Date(currentDateqw.value);
    selecttoday.value = formatDateToYearAndMonthDay(newdate);
  }

  nextTick(async () => {
    try {
      const ree = await getschedulemonth({
        shop_id: scheduledata.selfid,
        month: selecttoday.value,
      });

      if (ree.code == "200") {
        // ree.data.forEach((item: { flag: string; day: any }) => {
        //   if (item.flag == "1") {
        //     checkInDates1.value.push(item.day as never);
        //   } else if (item.flag == "3") {
        //     checkInDates3.value.push(item.day as never);
        //   } else if (item.flag == "4") {
        //     checkInDates4.value.push(item.day as never);
        //   }
        // });

        ree.data.forEach((item: { day: string; flag: any }) => {
          // 获取day的日期部分作为key
          const dayKey = item.day;
          MonthFlags.value[dayKey] = item.flag;
        });
      } else {
        console.error("日历flag查询失败");
      }

      const response = await getscheduleList({
        shop_id: scheduledata.selfid,
        day: selecttoday.value,
      });

      if (response.data[0].is_manager == "1") {
        tijiaoflack.value = true;
      } else {
        tijiaoflack.value = false;
      }

      yuanshidata.value = response.data;

      if (response.data.length > 0 && !(typeof response.data == "string")) {
        response.data[0].scheduleList.forEach(
          (element: { flag: string; day: string; userid: any; week: any }, key: any) => {
            const as = element.day.toString();
            const aa = as.split(" ");
            const bb = aa[0].split("-");

            weekDays.value[key] = `${element.week} ${bb[0]}-${bb[1]}-${bb[2]}`;
          }
        );
      }

      rawData.value = response.data;

      loading.value = false;
    } catch (error) {
      console.error("Failed to fetch data:", error);
    }
    loading.value = false;
  });
};

// 存储从API获取的数据格式化
const rawData = ref([]);
// 原始数据
const yuanshidata = ref([]);

// 在组件挂载时调用getlist函数
onMounted(() => {
  getlist();
});

// 当周数据提交按钮
const tijiao = async () => {
  if (
    MonthFlags.value[selecttoday.value] == "1" ||
    MonthFlags.value[selecttoday.value] == "3"
  ) {
    ElMessage({
      message: "当周数据已经提交不能再进行提交",
      type: "warning",
    });
  } else {
    try {
      const res = await putscheduleList({
        day: selecttoday.value,
        shop_id: scheduledata.selfid,
        flag: "3",
      });

      if (res.code == "200") {
        ElMessage.success("提交成功");
        getlist();
      } else {
        ElMessage.error("提交失败");
      }
    } catch (error) {
      console.error("Failed to fetch data:", error);
    }
  }
};

// 格式化数据以便于在表格中显示
const formattedData = computed(() => {
  if (rawData.value.length > 0 && !(typeof rawData.value == "string")) {
    return (
      rawData.value?.map((item: any) => ({
        in_out: item.in_shop,
        userid: item.userid,
        full_work: item.full_work,
        username: item.username,
        scheduleMap: item.scheduleList.reduce((acc: any, cur: any) => {
          cur.userid = item.userid;
          acc[cur.week] = cur;
          return acc;
        }, {}),
      })) || []
    );
  } else {
    return [];
  }
});

// 获取特定日期的排班信息
const getScheduleInfo = (scheduleMap: any, day: any) => {
  const aa = day;
  const cc = aa.split(" ");
  let schedule = scheduleMap[cc[0]];

  if (schedule.rest_type == "200") {
    return ["2", "正常上班"];
  } else if (schedule.rest_name) {
    return ["1", `排休 ${schedule.rest_name}`];
  } else {
    return ["0", "无排班"];
  }
};

// 返回信息用于展示调拨情况
const getdiaobo = (scheduleMap: any, day: any) => {
  return scheduleMap[day.toString().split(" ")[0]].in_out;
};

// 弹框标题日期
const heardtital = ref("");

// 添加班次
const bancitow = ref(false);

// 非全职人员中途休息时间
const midwayBreak = reactive({
  start_break: "",
  end_break: "",
  start_break2: "",
  end_break2: "",
});

const supplementTimeflack = ref(false);

// 收集数据班次时间点
const formData = reactive({
  vacationtype: "",
});

// 要发送的数据
const formDataqw = reactive({
  userid: "",
  shop_id: "",
  day: "",
  week: "",
  across: 0,
  section_num: 0,
  schedule_detail: [],
  is_rest: "",
  rest_type: "0",
});

// 抽屉取消按钮
const handlecancel = () => {
  supplementTimeflack.value = false;
  dialogVisible.value = false;
  bancitow.value = false;
  Object.assign(formData, {
    vacationtype: "",
  });
  Object.assign(midwayBreak, {
    start_break: "",
    end_break: "",
    start_break2: "",
    end_break2: "",
  });
};

// 表单校验规则
const rules = {
  vacationtype: [{ required: true, message: "请选择休假类型", trigger: "change" }],
};

// 判断是否提交过从而禁止修改
const zhoujinzhi = ref(<boolean>false);

// 假期的控制所有信息!!!!!!!!!!!!!!!!!!!!!!!
const isVaction = ref(<boolean>false);
const showvaction = ref(<boolean>false);

const vacationyve: vacationyvetype = ref([]);

// 点击事件处理函数
const handleClick = async (row: any, day: any) => {
  handlecancel();

  formDataqw.week = row.scheduleMap[day.toString().split(" ")[0]].week;

  //假期查询id
  vacationlog(false);
  vacationuseridlog.value = row.scheduleMap[day.toString().split(" ")[0]].userid;

  showvaction.value = true;
  // 排班回显
  if (row.scheduleMap[day.toString().split(" ")[0]].is_rest == 1) {
    // 请假回显
    formData.vacationtype = row.scheduleMap[day.toString().split(" ")[0]].rest_type;
  }

  heardtital.value = day.toString().split(" ")[1];

  // 当周数据已经提交不能再进行修改
  if (
    row.scheduleMap[day.toString().split(" ")[0]].flag == "1" ||
    row.scheduleMap[day.toString().split(" ")[0]].flag == "3"
  ) {
    zhoujinzhi.value = true;
    dialogVisible.value = true;
  } else {
    dialogVisible.value = true;
    formDataqw.userid = row.userid;
    formDataqw.shop_id = row.scheduleMap["星期一"].shop_id;
    formDataqw.day = heardtital.value;

    if (row.in_out != undefined && row.in_out != null) {
      //调出人员日期
      if (row.in_out == "1") {
        if (row.scheduleMap[day.toString().split(" ")[0]].in_out == "2") {
          zhoujinzhi.value = true;
        } else {
          zhoujinzhi.value = false;
        }
      } else if (row.in_out == "0") {
        if (row.scheduleMap[day.toString().split(" ")[0]].in_out == "0") {
          zhoujinzhi.value = true;
        } else {
          zhoujinzhi.value = false;
        }
      }
    }
  }

  //假期请求
  const res = await vacationpost({
    userid: formDataqw.userid,
  });
  vacationyve.value = res.data;
};

// 表单校验
const formRef = ref<FormInstance>();

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();

    if (formData.vacationtype == "200") {
    } else {

      for (const item of vacationyve.value) {
        if (item.leave_code == formData.vacationtype) {
          if (item.quota_num <= 0) {
            ElMessage.warning("假期余额为0不能再休假");
            return;
          }
        }
      }
    }

    if (formData.vacationtype) {
      formDataqw.schedule_detail = [];
      formDataqw.is_rest = "1";
      formDataqw.rest_type = formData.vacationtype;
    } else {
      formDataqw.is_rest = "0";
      formDataqw.rest_type = "";
    }

    formDataqw.shop_id = scheduledata.selfid as string;

    const res = await unbdatascheduleList(formDataqw);

    if (res.code == "200") {
      ElMessage.success("保存成功");

      getformDatalist();

      handlecancel();
      // getlist();
      dialogVisible.value = false;
    } else {
      ElMessage.error("保存失败");
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

//排班删除
const deleteschedule = async (row: any, day: any) => {
  try {
    const res = await delschedule({
      userid: row[day.toString().split(" ")[0]].userid,
      day: row[day.toString().split(" ")[0]].day,
      shop_id: row[day.toString().split(" ")[0]].shop_id,
    });

    if (res.code == "200") {
      ElMessage.success("排班删除成功");
      getformDatalist();
    } else {
      ElMessage.error("排班删除失败");
    }
  } catch (error) {
    console.error(error);
  }
};

// 控制排班删除按钮
const isDeleteschedule = (row: any, day: any) => {
  if (
    row[day.toString().split(" ")[0]].in_out == 2 ||
    // WeekFlags.value[row[day.toString().split(" ")[0]].day] == "1" ||
    // WeekFlags.value[row[day.toString().split(" ")[0]].day] == "3" ||

    MonthFlags.value[selecttoday.value] == "1" ||
    MonthFlags.value[selecttoday.value] == "3"
  ) {
    return true;
  } else {
    // if (
    //   row[day.toString().split(" ")[0]].flag == 1 ||
    //   row[day.toString().split(" ")[0]].flag == 3
    // ) {
    //   return true;
    // } else {
    //   return false;
    // }
    return false;
  }
};
</script>

<style scoped lang="scss">
.getScheduleInfostyle {
  width: 100%;

  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}
.getScheduleInfostylecorlor {
  color: #b69510;
}
.paixiucoler {
  color: #009107;
}
.diaoru {
  display: block;
  width: 50px;
  background-color: #fef6d5;
  border-radius: 5px;
  margin: 0 auto;
}
.zhengchang {
  display: block;
  width: 50px;
  background-color: #56bc5b;
  border-radius: 5px;
  margin: 0 auto;
}
.diaochu {
  display: block;
  width: 50px;
  background-color: #e96725;
  border-radius: 5px;
  margin: 0 auto;
}
.wustyle {
  display: block;
  width: 50px;
  background-color: #c0c4cc;
  border-radius: 5px;
  margin: 0 auto;
}
.el-radio {
  width: 50px;
}

.kuaban {
  position: absolute;
  top: 8px;
  left: 52%;
  border-radius: 8px;
  background-color: #fff0f0;
  border: 1px solid red;
  color: red;
  display: inline-block;
  width: 40px;
  text-align: center;
  line-height: 24px;
  height: 25px;
}

.signed-in1 {
  border-radius: 3px;
  overflow: hidden;
  display: inline-block;
  text-align: center;
  width: 100%;
  height: 100%;
  background-color: rgb(86, 139, 86) !important;
  color: white;
  cursor: not-allowed;
}

.signed-in3 {
  border-radius: 3px;
  overflow: hidden;
  display: inline-block;
  text-align: center;
  width: 100%;
  height: 100%;
  background-color: #ceb753 !important;
  color: white;
  cursor: not-allowed;
}

.signed-in4 {
  border-radius: 3px;
  overflow: hidden;
  display: inline-block;
  text-align: center;
  width: 100%;
  height: 100%;
  background-color: #e96725 !important;
  color: white;
  cursor: not-allowed;
}

.timesheet-container {
  padding: 20px;
  background: #fff;

  .content-area {
    display: flex;
    gap: 20px;

    .calendar-section {
      flex: 0 0 320px;

      :deep(.el-calendar) {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
      }
    }

    .timesheet-section {
      flex: 1;

      :deep(.el-input-number) {
        width: 100%;
      }
    }
  }
}

body {
  margin: 0;
}
.timesheet-section {
  .el-table {
    :deep(.el-table__header) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
        text-align: center;
      }
    }

    :deep(.el-table__body) {
      td {
        text-align: center;
      }
    }
  }

  .el-input-number {
    width: 100%;
  }
}

.balance-dialog {
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .el-dialog__close {
      font-size: 18px;
      color: #909399;
    }
  }

  :deep(.el-dialog__body) {
    padding: 24px 20px;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 20px;
    border-top: 1px solid #dcdfe6;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  .el-button {
    padding: 8px 20px;
    min-width: 80px;
    height: 32px;
    line-height: 1;
  }
}

.card-content {
  p {
    span:first-child {
      margin-right: 6px;
    }
  }
}
</style>
